package com.jsmtr.rms.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.utils.StringTools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.service.IBaseEvaluationService;
import com.jsmtr.rms.service.IBaseExaminerService;
import com.jsmtr.rms.service.IDoMSService;
import com.jsmtr.rms.service.IDoZZService;
import com.jsmtr.rms.service.IRecommendService;
import com.jsmtr.rms.service.ISchoolService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.EnumTools;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 中高职面试控制器
 * @author cyx
 * @date 2018/11/8 10:25
 */
@Controller
@RequestMapping("/Do/ZZInterview")
public class DoZZInterviewController {

    @Resource
    private IBaseEvaluationService baseEvaluationService;
    @Resource
    private IBaseExaminerService baseExaminerService;
    @Resource
    private IUtilService utilService;
    @Resource
    private IRecommendService recommendService;
    @Resource
    private ISchoolService schoolService;
    @Resource
    private IDoZZService doZZService;
    @Resource
    private IDoMSService msService;

    //[start] 查询毕业生信息

    @RequestMapping("/")
    public String Index(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String pid = request.getParameter("pid").trim();
            String fid = request.getParameter("fid").trim();
            String deptcode = request.getParameter("deptcode").trim();

            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);

            StringBuilder str = new StringBuilder();
            List<HRSchoolUsers> schools = schoolService.getSchools();
            for (HRSchoolUsers school : schools) {
                str.append("<option value='" + school.getId() + "'>" + school.getUname() + "</option>");
            }
            model.addAttribute("school", str);

            //评价表
            List<BaseEvaluationTable> tables = baseEvaluationService.getTables();
            StringBuilder evaluation = new StringBuilder();
            for (BaseEvaluationTable table : tables) {
                evaluation.append("<option value='" + table.getId() + "'>" + table.getName() + "</option>");
            }
            model.addAttribute("evaluation", evaluation);

            //面试地址
            model.addAttribute("dz", utilService.getAddress());

            //面试组
            List<BaseExaminerGroup> groups = baseExaminerService.getGroups();
            StringBuilder examiner = new StringBuilder();
            for (BaseExaminerGroup group : groups) {
                examiner.append("<option value='" + group.getId() + "'>" + group.getName() + "</option>");
            }
            model.addAttribute("examiner", examiner);

            List<BaseConfig> _configs = utilService.getConfigs("dxmb");
            StringBuilder str1 = new StringBuilder();
            for (BaseConfig _config : _configs) {
                str1.append("<option value='" + _config.getCode() + "'>" + _config.getName() + "</option>");
            }
            model.addAttribute("dxmb", str1);

            //状态
            List<ProjectInfoJobs> projectJobs=utilService.getProjectJobs(pid);
            model.addAttribute("jobs",projectJobs);
            List states=new ArrayList();
            List stateList=utilService.groupZZStateByFid(fid,"面试");
            if (stateList!=null&&stateList.size()>0){
                states.addAll(stateList);
            }else{
                states.add("未面试");
            }
            model.addAttribute("states",states);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "Do/ZZCampus/Interview/index";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getusers")
    public void getusers(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();
            String msresult = request.getParameter("mresult").trim();//面试结果
            int notice = Integer.parseInt(request.getParameter("notice"));//面试计划发布情况
            String msarrange=request.getParameter("msarrange");
            String scorearea=request.getParameter("scorearea");
            Map<String, Object> map = doZZService.getMSUsersMap(page, perpage, user, flowid, msresult, notice,msarrange,scorearea);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                List<HashMap> object = (List<HashMap>)map.get("list");
                for (HashMap<String,Object> _user :  object) {
                    //r.id,u.id as userid,r.name,r.gender,r.code,r.major,r.deptname,
                    //u.starttime,u.address,u.notice,u.point,u.result,,r.fid,r.fqstate,r.op2,r.scoringrules,r.msstate
                    result.append("<tr><td><input type=\"checkbox\" id='cb_" +  _user.get("ID")  + "' value='" + _user.get("ID") + "'/></td>");

                    result.append("<td class='link'><a target='_blank' href='"
                            + request.getContextPath() + "/UserResume/ViewDResume?id="
                            + _user.get("DRID") + "'>" + _user.get("NAME")
                            + "</a></td>");//简历ID和HRZZUser的ID相同
                    result.append("<td>" + _user.get("GENDER") + "</td>");
                    result.append("<td>" + _user.get("CODE") + "</td>");
                    result.append("<td>" + _user.get("MAJOR") + "</td>");
                    result.append("<td>" + _user.get("JOB") + "</td>");
                    result.append("<td>" + (_user.get("STARTTIME") == null ? "" : _user.get("STARTTIME")) + "</td>");
                    result.append("<td>" + (_user.get("ADDRESS") == null ? "" : _user.get("ADDRESS")) + "</td>");
                    result.append("<td class='link'><a href=\"javascript:viewEvaluation('" + _user.get("USERID") + "');\">" + (_user.get("STARTTIME") == null ? "" : "评价表") + "</a></td>");
                    result.append("<td class='link'><a href=\"javascript:viewExaminer('" + _user.get("ID") + "');\">" + (_user.get("STARTTIME") == null ? "" : "面试组") + "</a></td>");
                    result.append("<td>" + (_user.get("NOTICE") == null ? "" : EnumTools.NoticeState.values()[((BigDecimal) _user.get("NOTICE")).intValue()]) + "</td>");
                    result.append("<td class='link'>" + (_user.get("POINT") == null ? "" : "<a href=\"javascript:viewResult('" + _user.get("USERID") + "','" + _user.get("GENDER")+ "');\">" + _user.get("POINT")+ "</a>") + "</td>");
                    result.append("<td>" + (_user.get("RESULT")== null ? "" : _user.get("RESULT")) + "</td>");
                    result.append("<td>" + (_user.get("SCORINGRULES")== null ? "" : _user.get("SCORINGRULES")) + "</td>");
                   /* result.append("<td>" + (_user[16] == null ? "" : _user[16]) + "</td>");*/
                    if (_user.get("OP2").equals("未公布")) {
                        result.append("<td class='true'><span>" + _user.get("OP2") + "</span></td>");
                    } else {
                        result.append("<td class='false'><span>" + _user.get("OP2") + "</span></td>");
                    }

                    /*if (_user.get("FQSTATE").equals("已放弃") && _user.get("FID").equals(flowid)) {
                        result.append("<td class='yfq'><span>已放弃</span></td></tr>");
                    } else {
                        if (_user.get("RESULT") == null) {
                            result.append("<td class='true'><span>未完成</td></tr>");
                        } else {
                            if (_user.get("RESULT").equals("无结果")) {
                                result.append("<td class='true'><span>未完成</td></tr>");
                            } else if (_user.get("RESULT").equals("未通过")||_user.get("RESULT").equals("不通过")) {
                                result.append("<td class='false'><span>已完成</td></tr>");
                            } else {
                                if (_user.get("FID").equals(flowid)) {
                                    result.append("<td class='true'><span>未完成</td></tr>");
                                } else {
                                    result.append("<td class='false'><span>已完成</td></tr>");
                                }
                            }
                        }
                    }*/

                    result.append("<td>");
                    if (_user.get("FQSTATE").equals("已放弃") && _user.get("FQFID").equals(flowid)) {
                        // result.append("<td class='yfq'><span>已放弃</span></td></tr>");
                        result.append("<span class='layui-badge layui-bg-gray' title='已放弃'>弃</span>");
                    } else {

                        if (_user.get("RESULT") == null) {
                            // result.append("<td class='true'><span>未完成</td></tr>");
                            result.append("<span class='layui-badge layui-bg-orange' title='未完成'>未</span>");
                        } else {
                            if (_user.get("RESULT").equals("未面试")) {
                                //result.append("<td class='true'><span>未完成</td></tr>");
                                result.append("<span class='layui-badge layui-bg-orange' title='未完成'>未</span>");
                            } else if (_user.get("RESULT").equals("未通过")||_user.get("RESULT").equals("不通过")||_user.get("RESULT").equals("不合格")||_user.get("RESULT").equals("未参加")) {
                                // result.append("<td class='false'><span>已完成</td></tr>");
                                result.append("<span class='layui-badge layui-bg-green' title='已完成'>完</span>");
                            } else {
                                if (_user.get("FID").equals(flowid)) {
                                    // result.append("<td class='true'><span>未完成</td></tr>");
                                    result.append("<span class='layui-badge layui-bg-orange' title='未完成'>未</span>");
                                } else {
                                    //result.append("<td class='false'><span>已完成</td></tr>");
                                    result.append("<span class='layui-badge layui-bg-green' title='已完成'>完</span>");
                                }
                            }
                        }
                    }
                    if (_user.get("NRID") != null) {
                        result.append("<td class='ytj'><span title='" +  _user.get("NJNAME") + "'>已推荐</span></td></tr>");
                    }
                    result.append("</td>");
                    result.append("</tr>");
                }
            } else {
                result.append("<tr><td colspan='18'>未找到符合条件的数据</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='16'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }
    //[end]

    @ResponseBody
    @RequestMapping(value = "/getZzInterviewListLayuiJson", method = RequestMethod.GET)
    public LayuiDataTableResultBean getZzInterviewListLayuiJson(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String flowid = request.getParameter("flowid").trim();

            String msresult = request.getParameter("mresult").trim();//面试结果
            int notice = Integer.parseInt(request.getParameter("notice"));//面试计划发布情况
            String msarrange=request.getParameter("msarrange");
            String scorearea=request.getParameter("scorearea");
            Map<String, Object> map = doZZService.getMSUsersMap(page, limit, user, flowid, msresult, notice,msarrange,scorearea);

            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            JSONArray jsonArray = new JSONArray();
            int num = 1;
            if (pageCount != 0) {
                List<HashMap> object = (List<HashMap>) map.get("list");
                for (HashMap<String, Object> _user : object) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id_cb", "cb_" + _user.get("ID"));
                    jsonObject.put("id", limit * (page - 1) + num);
                    jsonObject.put("NAME", _user.get("NAME"));
                    jsonObject.put("cardcount", (_user.get("CARDCOUNT") == null ? 0 :Integer.parseInt(_user.get("CARDCOUNT").toString())));
                    jsonObject.put("ContextPath", request.getContextPath() + "/UserResume/ViewDResume?id=" + _user.get("DRID"));
                    jsonObject.put("SEXNAME", _user.get("GENDER"));
                    jsonObject.put("CARDNO", _user.get("CODE"));
                    jsonObject.put("MAJORNAME", (_user.get("MAJOR") == null ? "" : _user.get("MAJOR")));
                    jsonObject.put("JOB",  (_user.get("JOB") == null ? "" : _user.get("JOB")));
                    jsonObject.put("STARTTIME", (_user.get("STARTTIME") == null ? "" : _user.get("STARTTIME")));
                    jsonObject.put("ADDRESS", (_user.get("ADDRESS") == null ? "" : _user.get("ADDRESS")));
                    jsonObject.put("USERID", _user.get("USERID") );
                    jsonObject.put("IDs", _user.get("ID") );
                    jsonObject.put("NOTICE", (_user.get("NOTICE") == null ? "" : EnumTools.NoticeState.values()[((BigDecimal) _user.get("NOTICE")).intValue()]));

                    jsonObject.put("POINT", (_user.get("POINT") == null ? "" : _user.get("POINT")));
                    jsonObject.put("RESULT", (_user.get("RESULT") == null ? "" : _user.get("RESULT")));
                    jsonObject.put("SCORINGRULES", (_user.get("SCORINGRULES") == null ? "" : _user.get("SCORINGRULES")));
                    jsonObject.put("MID", _user.get("MID"));
                    jsonObject.put("MCONTENT", (_user.get("MCONTENT") == null ? "" : _user.get("MCONTENT")));

                    if (_user.get("OP2").equals("未公布")) {
                        jsonObject.put("STATEb", "未公布");
                    } else {
                        jsonObject.put("STATEb","已公布");
                    }

                    jsonObject.put("FQSTATE", _user.get("FQSTATE"));
                    jsonObject.put("FQFID", _user.get("FQFID"));
                    jsonObject.put("FID", _user.get("FID"));

                    if (_user.get("FQSTATE").equals("已放弃") && _user.get("FQFID").equals(flowid)) {
                        jsonObject.put("STATEc", "弃");
                    } else {

                        if (_user.get("RESULT") == null) {
                            jsonObject.put("STATEc", "未");
                        } else {
                            if (_user.get("RESULT").equals("未面试")) {
                                jsonObject.put("STATEc", "未");
                            } else if (_user.get("RESULT").equals("未通过")||_user.get("RESULT").equals("不通过")||
                                    _user.get("RESULT").equals("不合格")||_user.get("RESULT").equals("未参加")) {
                                jsonObject.put("STATEc", "完");
                            } else {
                                if (_user.get("FID").equals(flowid)) {
                                    jsonObject.put("STATEc", "未");
                                } else {
                                    jsonObject.put("STATEc", "完");
                                }
                            }
                        }
                    }

                    if (StringTools.trimNotEmpty(_user.get("NRID"))){
                        jsonObject.put("NJNAME", _user.get("NJNAME"));
                        jsonObject.put("STATEd", "已推荐");
                        jsonObject.put("NRID", _user.get("NRID"));
                    }else
                        jsonObject.put("NRID", "");

                    jsonObject.put("arrange", _user.get("MSARRANGE"));

                    jsonArray.add(jsonObject);
                    num++;
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount((int) allcount);
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

            @Deprecated
    public void getusers_bak(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();
            String msresult = request.getParameter("msstate").trim();//面试结果
            int notice = Integer.parseInt(request.getParameter("notice"));//面试计划发布情况
            String msarrange=request.getParameter("msarrange");

            Map<String, Object> map = doZZService.getMSUsers(page, perpage, user, flowid, msresult, notice,msarrange);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                for (Object[] _user : (List<Object[]>) object) {
                    //r.id,u.id as userid,r.name,r.gender,r.code,r.major,r.deptname,
                    //u.starttime,u.address,u.notice,u.point,u.result,,r.fid,r.fqstate,r.op2,r.scoringrules,r.msstate
                    result.append("<tr><td><input type=\"checkbox\" id='cb_" + _user[0] + "' value='" + _user[0] + "'/></td>");
                    result.append("<td>" + _user[2] + "</td>");
                    result.append("<td>" + _user[3] + "</td>");
                    result.append("<td>" + _user[4] + "</td>");
                    result.append("<td>" + _user[5] + "</td>");
                    result.append("<td>" + _user[6] + "</td>");
                    result.append("<td>" + (_user[7] == null ? "" : _user[7]) + "</td>");
                    result.append("<td>" + (_user[8] == null ? "" : _user[8]) + "</td>");
                    result.append("<td class='link'><a href=\"javascript:viewEvaluation('" + _user[1] + "');\">" + (_user[7] == null ? "" : "评价表") + "</a></td>");
                    result.append("<td class='link'><a href=\"javascript:viewExaminer('" + _user[1] + "');\">" + (_user[7] == null ? "" : "面试组") + "</a></td>");
                    result.append("<td>" + (_user[9] == null ? "" : EnumTools.NoticeState.values()[((BigDecimal) _user[9]).intValue()]) + "</td>");
                    result.append("<td class='link'>" + (_user[10] == null ? "" : "<a href=\"javascript:viewResult('" + _user[1] + "','" + _user[3] + "');\">" + _user[10] + "</a>") + "</td>");
                    result.append("<td>" + (_user[11] == null ? "" : _user[11]) + "</td>");
                    result.append("<td>" + (_user[15] == null ? "" : _user[15]) + "</td>");
                    /* result.append("<td>" + (_user[16] == null ? "" : _user[16]) + "</td>");*/
                    if (_user[14].equals("未公布")) {
                        result.append("<td class='true'><span>" + _user[14] + "</span></td>");
                    } else {
                        result.append("<td class='false'><span>" + _user[14] + "</span></td>");
                    }
                    if (_user[13].equals("已放弃") && _user[12].equals(flowid)) {
                        result.append("<td class='yfq'><span>已放弃</span></td></tr>");
                    } else {
                        if (_user[11] == null) {
                            result.append("<td class='true'><span>未完成</td></tr>");
                        } else {
                            if (_user[11].equals("无结果")) {
                                result.append("<td class='true'><span>未完成</td></tr>");
                            } else if (_user[11].equals("未通过")||_user[11].equals("不通过")) {
                                result.append("<td class='false'><span>已完成</td></tr>");
                            } else {
                                if (_user[12].equals(flowid)) {
                                    result.append("<td class='true'><span>未完成</td></tr>");
                                } else {
                                    result.append("<td class='false'><span>已完成</td></tr>");
                                }
                            }
                        }
                    }
                }
            } else {
                result.append("<tr><td colspan='15'>未找到符合条件的数据</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='15'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }
    //[start] 流程扭转到下一步

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/NextAction", method = RequestMethod.POST)
    public void NextAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");//人员信息ID
            if (ids != null) {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(deptcode)) {
                    List editlist = new ArrayList();
                    List<HRZZUser> users = doZZService.getUsers(pid, deptcode, ids);
                    ProjectInfoFlow nFlow = doZZService.getNextFlow(pid, deptcode, fid);
                    for (HRZZUser user : users) {
                        if (user.getFid().equals(fid) && user.getFqstate().equals("未放弃")) {
                            DoMSUser msuser = msService.getMsUser(fid, user.getId());
                            if (msuser.getResult().equalsIgnoreCase("已通过")||msuser.getResult().equalsIgnoreCase("通过")||msuser.getResult().equalsIgnoreCase("合格")) {
                                user.setFid(nFlow.getId());
                                user.setPath(user.getPath() + nFlow.getId() + "/");
                                editlist.add(user);
                            }
                        }
                    }
                    if (editlist.size() > 0) {
                        nFlow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                        editlist.add(nFlow);

                        utilService.editList(editlist);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "当前选中的信息不能执行此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "请选择人员信息！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]
}
